<template>
  <a-page-header
    style="border: 1px solid rgb(235, 237, 240); margin-bottom: 10px"
    title="yunexam在线考试系统"
    sub-title="管理员登录"
  />
  <a-form ref="formRef" :model="loginFormState" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
    <a-form-item label="用户名" name="username">
      <a-input v-model:value="loginFormState.username" />
    </a-form-item>
    <a-form-item label="密码" name="password">
      <a-input v-model:value="loginFormState.password" type="password" />
    </a-form-item>
    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" @click="onSubmit">登录</a-button>
      <a-button style="margin-left: 10px" @click="resetForm">重置</a-button>
    </a-form-item>
  </a-form>
</template>

<script>
import { message } from "ant-design-vue";
import { defineComponent, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { adminLogin } from "../../utils/api";

export default defineComponent({
  setup() {
    const formRef = ref();
    const router = useRouter();
    const loginFormState = reactive({
      username: "",
      password: "",
    });

    const rules = {
      username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
      password: [{ required: true, message: "请输入密码", trigger: "blur" }],
    };

    const onSubmit = () => {
      formRef.value
        .validate()
        .then(async () => {
          let result = await adminLogin(loginFormState);
          // 登录失败
          if (result.data.code === 500) {
            message.info(result.data.message);
            return;
          }
          // 登录成功跳转
          router.push({ name: "AdminIndex" });
        })
        .catch((error) => {
          console.log("error", error);
        });
    };

    const resetForm = () => {
      formRef.value.resetFields();
    };

    return {
      formRef,
      rules,
      loginFormState,
      onSubmit,
      resetForm,
      labelCol: {
        span: 4,
      },
      wrapperCol: {
        span: 14,
      },
    };
  },
});
</script>
